/**
 * Created by lenovo on 2017/1/8.
 */
import store from '@/store'
import {getCache, copy, getDicByIdFor, getTimeByMs, m7Language, checkHideTel} from './m7Utils.js'
import {trim, uniq} from 'lodash'
import { common } from '@/utils/cosUrl'

export function hasAccessForFlow (flow) {
  let result = false
  if (flow.status === 'disable') {
    return result
  }
  let stepItem = getStartStep(flow)
  if (!stepItem) {
    return result
  }
  let roles = getStepRoles(stepItem._id)
  let queues = getStepQueues(stepItem._id)
  for (let j = 0; j < roles.length; j++) {
    let rolesItem = roles[j]
    if (arrayContainsStr(store.state.session.user.role, rolesItem)) {
      result = true
    }
  }
  // 技能组
  for (let j = 0; j < queues.length; j++) {
    let queuesItem = queues[j]
    if (arrayContainsStr(store.state.session.user.mixedBizScope, queuesItem)) {
      result = true
    }
  }
  return result
}
export function getStartStep (flow) {
  let steps = (flow && flow.steps) ? flow.steps : []
  for (let i = 0; i < steps.length; i++) {
    if (steps[i].isBegin) {
      return steps[i]
    }
  }
  return ''
}
export function getFlowStepById (flow, id) {
  let steps = (flow && flow.steps) ? flow.steps : []
  for (let i = 0; i < steps.length; i++) {
    if (steps[i]._id === id) {
      return steps[i]
    }
  }
  return ''
}
export function getStepRoles (stepId) {
  let step = getCache('businessFlowStep', stepId)
  let actions = (step && step.actions) ? step.actions : []
  let roles = []
  for (let i = 0; i < actions.length; i++) {
    let actionsItem = actions[i]
    // 兼容老数据，之前是字符串
    if (!Array.isArray(actionsItem.actionRole)) {
      actionsItem.actionRole = [actionsItem.actionRole]
    }
    actionsItem.actionRole.forEach(item => {
      roles.push(item)
    })
  }
  return roles
}
export function getStepQueues (stepId) {
  let step = getCache('businessFlowStep', stepId)
  let actions = (step && step.actions) ? step.actions : []
  let queues = []
  for (let i = 0; i < actions.length; i++) {
    let actionsItem = actions[i]
    if (actionsItem.actionQueue) {
      actionsItem.actionQueue.forEach(item => {
        queues.push(item)
      })
    }
  }
  return queues
}
export function arrayContainsStr (array, str) {
  array = array || []
  for (let i = 0; i < array.length; i++) {
    if (str) {
      if (array[i] === str) {
        return true
      } else if (str.includes(array[i])){
        return true
      }
    }
  }
  return false
}
export function getObjectById (datas, id) {
  datas = datas || []
  for (let i = 0; i < datas.length; i++) {
    let datasItem = datas[i]
    if (datasItem._id === id) {
      return copy(datasItem)
    }
  }
  return null
}
export function getFlowAction (flowId, actionId) {
  let flow = getCache('businessFlowStep', flowId)
  let actions = flow.actions || []
  for (let i = 0; i < actions.length; i++) {
    let actionsItem = actions[i]
    if (actionsItem._id === actionId) {
      return actionsItem
    }
  }
}
export function getRoleActions (stepItem) {
  let _actions = []
  if (!stepItem) {
    return []
  }
  let actions = stepItem.actions || []
  for (let i = 0; i < actions.length; i++) {
    let actionsItem = actions[i]
    if (arrayContainsStr(store.state.session.user.role, actionsItem.actionRole)) {
      _actions.push(actionsItem)
    }
    if (arrayContainsStr(store.state.session.user.mixedBizScope, actionsItem.actionQueue)) {
      _actions.push(actionsItem)
    }
  }
  return _actions
}
export function getRoleAgents (roles, filter, busCreateUser) {
  // 去重
  roles = [...new Set(roles)]
  let agents = getCache('agents')
  let result = []
  agents.forEach((item) => {
    if (filter && item.status === 'disable') {
      return
    }
    let agentRole = item.role || []
    let isHasRole = agentRole.find((one) => {
      return roles.includes(one)
    })
    if (isHasRole) {
      result.push(item)
    } else if (roles.includes('busCreateUser') && busCreateUser && busCreateUser === item._id) {
      result.push(item)
    }
  })
  // 用于工单设置
  if (roles.includes('busCreateUser') && busCreateUser === 'busConfig') {
    result.unshift({_id: 'busCreateUser', displayName: m7Language('business.businessCreate')})
  }
  return sortAgents(result)
}
export async function getQueueAgents (queues, filter) {
  // 去重
  let queueAgents = []
  queues = [...new Set(queues)]
  let res = await store.dispatch('getDicCache', {type: 'businessQueue'})
  if (res && res.success) {
    if (res.data.length > 0) {
      res.data.forEach(item => {
        if (queues.includes(item._id)) {
          if (item.Members) {
            queueAgents.push(...item.Members.map(item => {
              return item.id
            }))
          }
        }
      })
    }
  }
  let agents = getCache('agents')
  let result = []
  agents.forEach(item => {
    if (filter && item.status === 'disable') {
      return
    }
    if (queueAgents.includes(item._id)) {
      result.push(item)
    }
  })
  return sortAgents(result)
  // })
}
function sortAgents (agents) {
  agents = agents || []
  agents.sort(function (a, b) {
    if(a._id=='busCreateUser'||b._id=='busCreateUser'){
      return
    }else{
      if (a.pinyin && b.pinyin) {
        if (a.pinyin > b.pinyin) {
          return 1
        } else if (a.pinyin === b.pinyin) {
          return 0
        } else {
          return -1
        }
      } else {
        if (a.displayName > b.displayName) {
          return 1
        }else if (a.displayName === b.displayName) {
          return 0
        } else {
          return -1
        }
      }
    }
  })
  return agents
}
function initCascateSelectData (business, field, form) {
  let labels = []
  let dic = getDicFromField(field, getCache('custTmpls'), getCache('options')) || {}
  let options = dic.options || []
  // let selectOption = function (options, val) {
  //  options = options || []
  //  for (let opIndex = 0; opIndex < options.length; opIndex++) {
  //    if (options[opIndex].key === val) {
  //      return options[opIndex]
  //    }
  //  }
  //  return []
  // }
  // let defaultSelectValue = null
  for (let cascateIndex = 0; cascateIndex < (dic.cascade || 0); cascateIndex++) {
    // field.name = dic.headers[cascateIndex]
    let selectName = field._id
    if (cascateIndex !== 0) {
      selectName += '_' + cascateIndex
    }
    let label = {label: cascateIndex === 0 ? field.name : '  ', name: selectName, inputType: 'select', data: [{value: '', label: m7Language('public.all')}], cascadeIndex: cascateIndex}
    form[selectName] = null
    labels.push(label)
    if (cascateIndex === 0) {
      // let hasDic = false
      // if (!business[field._id]) {
      //  hasDic = true
      // }
      for (let i = 0; i < options.length; i++) {
        let optionsItem = options[i]
        label.data.push({value: optionsItem.key, label: optionsItem.name})
        // if ((business[field._id] && optionsItem.key === business[field._id])) {
        //  hasDic = true
        // }
      }
        // 设置默认值的,高级搜索不需要
      // if (hasDic) {
      //  form[selectName] = business[field._id] || field['default']
      //  label.selectValue = business[field._id] || field['default']
      //  defaultSelectValue = business[field._id] || field['default']
      // } else {
      //  form[selectName] = business[field._id + '_default']
      //  label.selectValue = business[field._id + '_default']
      //  defaultSelectValue = business[field._id + '_default']
      //  label.data.push({value: business[field._id + '_default'], label: business[field._id + '_default']})
      // }
    } else {
      // let lastVal = defaultSelectValue
    //  if (lastVal) {
    //    let hasDic = false
    //    if (!business[field._id + '_' + cascateIndex]) {
    //      hasDic = true
    //    }
    //    options = selectOption(options, lastVal).options || []
    //    for (let i = 0; i < options.length; i++) {
    //      let optionsItem = options[i]
    //      label.data.push({value: optionsItem.key, label: optionsItem.name})
    //      if (business[field._id + '_' + cascateIndex] && optionsItem.key === business[field._id + '_' + cascateIndex]) {
    //        hasDic = true
    //      }
    //    }
    //    if (hasDic) {
    //      form[selectName] = business[field._id + '_' + cascateIndex]
    //      label.selectValue = business[field._id + '_' + cascateIndex]
    //    } else {
    //      form[selectName] = business[field._id + '_' + cascateIndex + '_default']
    //      label.selectValue = business[field._id + '_' + cascateIndex + '_default']
    //      label.data.push({value: business[field._id + '_' + cascateIndex + '_default'], label: business[field._id + '_' + cascateIndex + '_default']})
    //    }
    //  }
    }
  }
  return labels
}
function initCheckBoxData (business, field) {
  let data = []
  let dic = getDicFromField(field, getCache('custTmpls'), getCache('options')) || {}
  let options = dic.options || []
  for (let i = 0; i < options.length; i++) {
    let optionsItem = options[i]
    if (arrayContainsStr(business[field._id], optionsItem.key)) {
      data.push({label: optionsItem.name, value: optionsItem.key, checked: 'checked'})
    } else {
      data.push({label: optionsItem.name, value: optionsItem.key})
    }
  }
  return data
}
function initRadioData (field) {
  let data = []
  let dic = getDicFromField(field, getCache('custTmpls'), getCache('options')) || {}
  let options = dic.options || []
  for (let i = 0; i < options.length; i++) {
    let optionsItem = options[i]
    if (field['default'] === optionsItem.key) {
      data.push({label: optionsItem.name, value: optionsItem.key, checked: 'checked'})
    } else {
      data.push({label: optionsItem.name, value: optionsItem.key})
    }
  }
  return data
}
export function createFlowCustomFields (customFields, flowFields, isAdvSearch) {
  let advFields = []
  let customForm = {}
  customFields = customFields || []
  console.log(customFields)
  for (let i = 0; i < customFields.length; i++) {
    let row = customFields[i]
    for (let j = 0; j < row.cols.length; j++) {
      let col = row.cols[j]
      for (let k = 0; k < col.fields.length; k++) {
        let field = col.fields[k]
        let cacheField = getObjectById(flowFields, field._id)
        if (cacheField) {
          let type = cacheField.type
          switch (type) {
            case 'single':
              advFields.push({label: cacheField.name, name: cacheField._id, inputType: 'input'})
              customForm[cacheField._id] = null
              break
            case 'multi':
              advFields.push({label: cacheField.name, name: cacheField._id, inputType: 'textarea'})
              customForm[cacheField._id] = null
              break
            case 'date':
              advFields.push({label: cacheField.name, name: cacheField._id, inputType: 'date'})
              customForm[cacheField._id] = null
              break
            case 'datetime':
              advFields.push({label: cacheField.name, name: cacheField._id, inputType: 'datetime'})
              customForm[cacheField._id] = null
              break
            case 'time':
              advFields.push({label: cacheField.name, name: cacheField._id, inputType: 'time'})
              customForm[cacheField._id] = null
              break
            case 'number':
              advFields.push({label: cacheField.name, name: cacheField._id, inputType: 'input', type: 'Number'})
              customForm[cacheField._id] = null
              break
            case 'dropdown':
              let selectLabels = initCascateSelectData({}, cacheField, customForm)
              selectLabels.forEach((label) => {
                advFields.push(label)
              })
              customForm[cacheField._id] = ''
              break
            case 'dropdownTree':
              let selectLabelsTree = initCascateSelectData({}, cacheField, customForm)
              selectLabelsTree.forEach((label) => {
                advFields.push(label)
              })
              customForm[cacheField._id] = ''
              break
            case 'checkbox':
              let checkData = initCheckBoxData({}, cacheField)
              advFields.push({label: cacheField.name, name: cacheField._id, inputType: 'checkbox', data: checkData})
              customForm[cacheField._id] = []
              break
            case 'radio':
              let radioData = initRadioData(cacheField)
              advFields.push({label: cacheField.name, name: cacheField._id, inputType: 'radio', data: radioData})
              customForm[cacheField._id] = null
              break
            case 'file':
              // if(isAdvSearch){
              //  break;
              // }else {
                // if (business && business[cacheField._id]) {
                //  if (handler.business.isStartStep(business.step) || business.isProcessAction) {
                //    let qid = uuid.v1();//考虑多个附件字段
                //    let fileContent = template("tmpl_bus_add_attach", {
                //      qiniuId: qid,
                //      _id: field._id
                //    });
                //    cacheField.fileContent = fileContent;
                //    colPane.append(render.replaceDataByObject(cacheField, fileTmp));
                //    utils.workflow._initQiniuUpload(qid, pane);
                //
                //    let attachs = business[cacheField._id] || [];
                //    let list = [];
                //    for (let l = 0; l < attachs.length; l++) {
                //      let obj = attachs[l];
                //      obj.fid = field._id;
                //      list.push(template("tmpl_bus_attach_show_edit", obj));
                //    }
                //    let containerId = qid + '-business-qiniu';
                //    let p1 = pane.find("#" + containerId).closest(".bus_attach_upload_container");
                //    let p1 = p1.find(".thumbnails_customer");
                //    p1.html(list.join(""));
                //  } else {
                //    let attachs = business[cacheField._id] || [];
                //    let list = [];
                //    for (let l = 0; l < attachs.length; l++) {
                //      let obj = attachs[l];
                //      obj.fid = field._id;
                //      list.push(template("tmpl_bus_attach_show", obj));
                //    }
                //    let _html = list.join("");
                //    if (list.length == 0) {
                //      _html = "<li style='margin-top: 3px;'>无</li>";
                //    }
                //    let html = '<ul class="thumbnails_customer">' + _html + '</ul>';
                //    cacheField.fileContent = html;
                //    colPane.append(render.replaceDataByObject(cacheField, fileTmp));
                //  }
                // } else {
                //  let qid = uuid.v1();
                //  let fileContent = template("tmpl_bus_add_attach", {
                //    qiniuId: qid,
                //    _id: field._id
                //  });
                //  cacheField.fileContent = fileContent;
                //  colPane.append(render.replaceDataByObject(cacheField, fileTmp));
                //  utils.workflow._initQiniuUpload(qid, pane);
                // }
              // }
              break
            default :
              console.log('the type [' + type + '] is not support!')
          }
        } else {
        }
      }
    }
  }
  return {advFields: advFields, customForm: customForm}
}
export function addBusienssSelectCascade (store, fieldValue, fieldId, casIndex, rootValue) {
  return new Promise((resolve, reject) => {
    store.dispatch('getCache', {type: 'businessFlowField', id: fieldId}).then((field) => {
      let dic = getDicFromField(field, getCache('custTmpls'), getCache('options')) || {}
      let casCount = Number(dic.cascade || 1)
      if (casIndex + 1 === casCount) {
        resolve([], casCount)
      }
      let fun = function (options, key) {
        options = options || []
        for (let i = 0; i < options.length; i++) {
          let optionsItem = options[i]
          if (optionsItem.key === key) {
            return options[i].options
          }
          let opts = optionsItem.options || []
          if (opts.length) {
            let result = fun(opts, key)
            if (result) {
              return result
            }
          }
        }
      }

      if (casIndex === 0) {
        let labels = [{label: m7Language('public.all'), value: ''}]
        let options = fun(dic.options, fieldValue) || []
        for (let i = 0; i < options.length; i++) {
          let optionsItem = options[i]
          labels.push({label: optionsItem.name, value: optionsItem.key})
        }
        resolve(labels, casCount)
      } else {
        let labels = [{label: m7Language('public.all'), value: ''}]
        let prevOtions = fun(dic.options, rootValue) || []
        let options = fun(prevOtions, fieldValue) || []
        for (let i = 0; i < options.length; i++) {
          let optionsItem = options[i]
          labels.push({label: optionsItem.name, value: optionsItem.key})
        }
        resolve(labels, casCount)
      }
    })
  })
}
export function getFlowStepNameByCache (flowId, stepId) {
  let flow = getCache('businessFlow', flowId)
  let steps = (flow && flow.steps) ? flow.steps : []
  for (let i = 0; i < steps.length; i++) {
    let stepsItem = steps[i]
    if (stepsItem._id === stepId) {
      return stepsItem.name
    }
  }
  return stepId
}
export function getTextFieldsNameByCache (flowId, field) {
  let flow = getCache('businessFlow', flowId)
  let textFields = (flow && flow.fields) ? flow.fields : []
  for (let i = 0; i < textFields.length; i++) {
     let textFieldsItem = textFields[i]
     if (textFieldsItem._id === field) {
       return textFieldsItem.name
     }
  }
  return field
}
export function getFlowStepActionById (actions, id) {
  actions = actions || []
  for (let i = 0; i < actions.length; i++) {
    let actionsItem = actions[i]
    if (actionsItem._id === id) {
      return actionsItem
    }
  }
  return {}
}
export function getBusinessStepActionName (stepId, actionId) {
  let step = getCache('businessFlowStep', stepId)
  let actions = (step && step.actions) ? step.actions : []
  for (let i = 0; i < actions.length; i++) {
    let actionsItem = actions[i]
    if (actionsItem._id === actionId) {
      return actionsItem.name
    }
  }
  return actionId
}
export function showCountDown (countDownTime) {
  let cc = ''
  let leftsecond = parseInt(Math.abs(countDownTime) / 1000)
  let hour = Math.floor(leftsecond / 3600)
  let minute = Math.floor((leftsecond - hour * 3600) / 60)
  let second = Math.floor(leftsecond - hour * 3600 - minute * 60)
  hour = checkTime(hour)
  minute = checkTime(minute)
  second = checkTime(second)
  cc = hour + ':' + minute + ':' + second
  return cc
}
export function getBusinessHisotryInfo (history, stepId, fromStep, actionId) {
  let action = history
  if (typeof history === 'object') {
    action = history.action
  }
  let result = {}
  if (!action) {
    result.error = m7Language('business.businessHistoryError')
    return result
  }
  if (stepId) {
    let step = getCache('businessFlowStep', stepId)
    result.action = action
    result.stepName = step ? step.name : ''
  }
  if (fromStep) {
    let fromstep = getCache('businessFlowStep', fromStep)
    result.fromStepName = fromstep ? fromstep.name : ''
    let status = ''
    if (history.excuteData) {
      status = history.excuteData.status
    }
    if (history.excuteUser === 'sys' || status === 'complete') {
      result.nextMaster = ''
    } else {
      // assignWay ：assign_1_1 技能组内自动分配 assign_1_0 角色内
      // assignWay没有的话害默认之前的 自动分配
      if (history.excuteData.assignWay && history.excuteData.assignWay === 'assign_1') {
        result.nextMaster = m7Language('public.randomAssign')
      } else if (history.excuteData.assignWay && history.excuteData.assignWay === 'assign_2') {
        result.nextMaster = m7Language('public.takeTurnsAssign')
      } else {
        if (history.excuteUser) {
          result.nextMaster = getUserNameById(history.excuteUser)
        } else {
          result.nextMaster = m7Language('public.autoAssign')
        }
      }
    }
  }
  if (action === 'create') {
    result.actionName = m7Language('business.createBusiness')
  } else if (action === 'transformIn') {
    let actionName = getBusinessStepActionName(fromStep, actionId)
    result.actionName = actionName
  } else if (action === 'backIn') {
    result.actionName = m7Language('business.backBusiness')
  } else if (action === 'recreate') {
    result.actionName = m7Language('business.reSaveBusiness')
  } else if (action === 'comment') {
    result.actionName = m7Language('business.addComments')
  } else if (action === 'share') {
    // 关注
    result.actionName = m7Language('business.changeFollowedAgents')
  } else if (action === 'configBusiness') {
    result.actionName = history.history_type === 'reply' ? '回复客户' : '客户回复'
  } else if (action === 'triggerSendSms' || action === 'triggerSendSatisfaction') {
    // 触发器发送短信
    let person = m7Language(`public.${history.excuteData.flag}`)
    let username = history.excuteData.name || ''
    result.actionName = m7Language('business.triggerSendSms', {person, username})
  } else if (action === 'triggerSendMail') {
    let username = (history.excuteData.name || []).join(', ')
    result.actionName = m7Language('business.triggerSendMail', {username})
  } else if (action === 'triggerOffline') {
    result.actionName = m7Language('business.triggerOffline')
  } else if (action === 'triggerAssign') {
    let username = getUserNameById(history.agent)
    result.actionName = m7Language('business.triggerAssign', {username})
  } else if (action === 'assign') {
    let username = getUserNameById(history.excuteData.master)
    if (username === history.excuteData.master) {
      username = m7Language('public.autoAssign')
    }
    result.actionName = m7Language('business.changeMaster', {username})
  } else if (action === 'changePriority') {
    let before = m7Language('business.priority' + history.excuteData.oldPriority)
    let current = m7Language('business.priority' + history.excuteData.newPriority)
    result.actionName = m7Language('business.changePriority', {before, current})
  } else if (action === 'urge') {
    result.actionName = m7Language('business.cuibanBusiness')
  } else {
    result.actionName = m7Language('business.unknownAction')
  }
  return result
}
export function getUserNameById (uid, maxLen) {
  if (!uid) {
    return uid
  }
  let user = getCache('agents', uid)
  if (user) {
    if (!maxLen) {
      return user.displayName
    } else {
      if (user.displayName.length > maxLen) {
        return user.displayName.substring(0, maxLen - 1) + '...'
      } else {
        return user.displayName
      }
    }
  }
  return uid
}
export function sortBusinessFields (items, flowfields, data, result, flag) {
  let cacheFiledIds = []
  let arr = []
  // 删除字段
  let arrDelete = []
  for (let i = 0; i < items.length; i++) {
    let row = items[i]
    for (let j = 0; j < row.cols.length; j++) {
      let col = row.cols[j]
      for (let k = 0; k < col.fields.length; k++) {
        let field = col.fields[k]
        let fieldDetail = flowfields.filter((item) => {
          return field._id === item._id
        })[0]
        if (!fieldDetail || data[field._id] === '') {
          continue
        }
        cacheFiledIds.push(field._id)
        businessFieldsItem(fieldDetail, data, arr, flag)
      }
    }
  }
  // 找到删除的字段
  if (flag !== 'card') {
    Object.keys(data).forEach((item) => {
      // 找到uuid
      if (item.length === 36 && !cacheFiledIds.includes(item)) {
        let fieldDetail = flowfields.find((one) => {
          return item === one._id
        })
        if (!fieldDetail) {
          return
        }
        businessFieldsItem(fieldDetail, data, arrDelete, flag)
      }
    })
    arrDelete.forEach((item) => {
      item.name = item.name + `(${m7Language('business.fieldRemove')})`
    })
  }
  result.push(...arr, ...arrDelete)
}
export function businessFieldsItem (field, data, result, flag) {
  if (field.type === 'dropdown' || field.type === 'dropdownTree') {
    let one = data[field._id + '_default'] || ''
    let two = data[field._id + '_1_default']
    let three = data[field._id + '_2_default']
    let four = data[field._id + '_3_default']
    let five = data[field._id + '_4_default']
    let comcat = one + (two ? '-->' + two : '') + (three ? '-->' + three : '') + (four ? '-->' + four : '') + (five ? '-->' + five : '')
    comcat ? result.push({_id: field._id, name: field.name, value: comcat,importantField:field.importantField}) : ''
  } else if (field.type === 'checkbox') {
    if (data[field._id] && data[field._id + '_default'] && data[field._id].length) {
      // 类型被改变报错
      let one = data[field._id + '_default']
      if (typeof data[field._id + '_default'] === 'string') {
        one = [data[field._id + '_default']]
      }
      result.push({_id: field._id, name: field.name, value: one.join(','),importantField:field.importantField})
    }
  } else if (field.type === 'radio') {
    if (data[field._id]) {
      result.push({_id: field._id, name: field.name, value: data[field._id + '_default'],importantField:field.importantField})
    }
  } else if (field.type === 'file') {
    if (flag === 'card') {
      return
    }
    let attachs = data[field._id] || []
    let html = []
    for (let l = 0; l < attachs.length; l++) {
      let obj = attachs[l]
      if (obj.id && obj.name) {
        // 确保字段类型更改不报错
        obj.url = common.getUrl(obj, { useAttname: true })
        obj.url2 = common.getUrl(obj, { noQuery: true })
        html.push(obj)
      }
    }
    if (html.length) {
      result.push({_id: field._id, name: field.name, value: html,importantField:field.importantField})
    }
  } else if (field.relevance === 'stable_phone' && data[field._id]) {
    let value = checkHideTel(data[field._id].toString(), store.state.session.user)
    result.push({_id: field._id, name: field.name, value,importantField:field.importantField})
  } else {
    if (data[field._id]) {
      result.push({_id: field._id, name: field.name, value: data[field._id].toString(),importantField:field.importantField})
    }
  }
}
export function getBusinessHistoryData (history, business, flag) {
  let data = history.excuteData || {}
  let result = {}
  let arr = []
  for (let m in data) {
    arr.push(m)
  }
  arr.sort()
  for (let i in arr) {
    let key = arr[i]
    let filedKey = key
    if (key.substring(key.length - 2, key.length - 1) === '_') {
      filedKey = key.substring(0, key.length - 2)
    }
    let field = getCache('businessFlowField', filedKey)
    if (field) {
      if (field.type === 'dropdown' || field.type === 'checkbox' || field.type === 'radio') {
        let dic = getDicByIdFor(data[key], getCache('options') || [])
        if (dic) {
          if (result[field.name]) {
            if (dic.name) {
              result[field.name] += ('-->' + dic.name)
            }
          } else {
            result[field.name] = dic.name
          }
        } else {
          if (result[field.name]) {
            if (data[key + '_default']) {
              result[field.name] += ('-->' + data[key + '_default'])
            }
          } else {
            if (field.type === 'checkbox') {
              if (data[key + '_default'] && data[key + '_default'].length) {
                result[field.name] = ''
                data[key + '_default'].forEach((item) => {
                  result[field.name] += item + ','
                })
                result[field.name] = result[field.name].substring(0, result[field.name].length - 1)
              } else {
                result[field.name] = ''
              }
            } else {
              result[field.name] = data[key + '_default'] || ''
            }
          }
        }
      } else if (field.type === 'file') {
        let attachs = data[key] || []
        let html = []
        for (var l = 0; l < attachs.length; l++) {
          let obj = attachs[l]
          obj.url = common.getUrl(obj, { useAttname: true })
          obj.url2 = common.getUrl(obj, { noQuery: true })
          html.push(obj)
        }
        result[field.name] = html
      } else {
        result[field.name] = data[key] || ''
      }
    } else {
      if (filedKey === 'number') {
        result[m7Language('business.businessNumber')] = data[key]
      } else if (filedKey === 'priority') {
        result[m7Language('business.priorityLabel')] = m7Language('business.priority' + data[key])
      }
    }
  }
  if (history.action === 'backIn') {
    result[m7Language('business.returnReason')] = data.backInfo
  } else if (history.action === 'comment') {
    result[m7Language('business.note')] = data.backInfo
  }
  return result
}
export function getBusinessHistoryDataNew (history, business, flag) {
  let data = history.excuteData || {}
  let result = []
  if (history.action === 'backIn') {
    // 退回工单
    result.push({name: m7Language('business.returnReason'), value: data.backInfo})
  } else if (history.action === 'comment' || history.action === 'configBusiness') {
    // 备注
    let attachs = data.attach || []
    let html = []
    for (let l = 0; l < attachs.length; l++) {
      let obj = attachs[l]
      obj.url = common.getUrl(obj, { useAttname: true })
      obj.url2 = common.getUrl(obj, { noQuery: true })
      html.push(obj)
    }
    result.push({name: history.action !== 'configBusiness' ? m7Language('business.note') : m7Language('business.replyContent'), value: data.backInfo})
    if (html.length) {
      result.push({name: m7Language('public.attach'), value: html})
    }
  } else if (history.action === 'share') {
    // 关注人
    let show = {}
    for (let item in data) {
      let arr = data[item] || []
      show[item] = []
      for (let i = 0; i < arr.length; i++) {
        show[item].push(getUserNameById(arr[i]))
      }
    }
    let current = show.currentFollowedAgents || []
    let before = show.beforeFollowedAgents || []
    let message = m7Language('business.currentFollowedAgents', {beforeFollowedAgents: before.join(','), currentFollowedAgents: current.join(',')})
    result.push({name: m7Language('business.followedAgents'), value: message})
  } else if (history.action === 'create' || history.action === 'recreate') {
    let flow = getCache('businessFlow', data.flow)
    if (flow) {
      let fields = flow.fields
      let step = getStartStep(flow)
      let stepFields = step.stepFields || []
      result.push({name: m7Language('business.businessNumber'), value: data.number})
      if (data.priority) {
        result.push({name: m7Language('business.priorityLabel'), value: m7Language('business.priority' + data.priority)})
      }
      sortBusinessFields(stepFields, fields, data, result)
    }
  } else if (history.action === 'transformIn') {
    // 执行过程
    let flow = getCache('businessFlow', business.flow) || {}
    let step = getCache('businessFlowStep', history.fromStep) || {}
    let actions = step.actions || []
    let action = actions.filter(function (item) {
      if (item._id === history.excuteAction) {
        return true
      }
    })
    let actionFields = action[0] ? action[0].actionFields : []
    let fields = flow.fields
    sortBusinessFields(actionFields, fields, data, result)
  } else if (history.action === 'assign') {
    // 变更处理人
  } else if (history.action === 'urge') {
    // 催办
    let urgeContent = data.urgeContent || ''
    result.push({name: m7Language('business.CuiBanContent'), value: urgeContent})
  }
  return result
}
export const serviceBusinessType = [
    {value: 'zxkf-mgc', label: '在线咨询-敏感词设置'},
    {value: 'zxkf-gxh', label: '在线咨询-个性化接待流程设置'},
    {value: 'zxkf-zxdj', label: '在线咨询-在线对接设置'},
    {value: 'zxkf-ly', label: '在线咨询-留言设置'},
    {value: 'hjzx-ivr', label: '呼叫中心-IVR配置'},
    {value: 'hjzx-jnz', label: '呼叫中心-技能组规则配置'},
    {value: 'gd-gd', label: '工单-工单配置'},
    {value: 'zj-zj', label: '质检-质检配置'},
    {value: 'js-js', label: '角色配置'}
]
export function taskTimeAll (ctype, ctime) {
  let resultStr
  if (ctype === 'day') {
    resultStr = ctime * 24 * 60 * 60 * 1000
  } else if (ctype === 'hours') {
    resultStr = ctime * 60 * 60 * 1000
  } else if (ctype === 'min') {
    resultStr = ctime * 60 * 1000
  } else if (ctype === 'second') {
    resultStr = ctime * 1000
  }
  return showCountDown(resultStr)
}
// export function timer (time) {
//   let ts = time // 计算剩余的毫秒数
//   let dd = parseInt(ts / 1000 / 60 / 60 / 24, 10)
//   let hh = parseInt(ts / 1000 / 60 / 60 % 24, 10)
//   let mm = parseInt(ts / 1000 / 60 % 60, 10)
//   let ss = parseInt(ts / 1000 % 60, 10)
//   hh = checkTime(hh)
//   mm = checkTime(mm)
//   ss = checkTime(ss)
//   if (dd > 0) {
//     return dd + m7Language('public.day2')
//   } else if (hh > 0) {
//     return hh + m7Language('public.hours2') + mm + m7Language('public.minutes') + ss + m7Language('public.seconds')
//   } else {
//     return mm + m7Language('public.minutes') + ss + m7Language('public.seconds')
//   }
// }
export function checkTime (i) {
  if (i < 10) {
    i = '0' + i
  }
  return i
}
export function busTimeDown (timeContent, currentBusiness, callBack) {
  let stepTimeState, totalTimeState
  if (currentBusiness.status === 'complete' || currentBusiness.status === 'cancel') {
    let totalExpireTime, stepExpireTime
    stepTimeState = 'business.stepTimeStateComplete'
    stepExpireTime = currentBusiness.processTime * 1000
    let flowObj = getCache('businessFlow', currentBusiness.flow)
    if (flowObj.ctype && flowObj.ctime) {
      totalExpireTime = getTimeByMs(flowObj.ctype, flowObj.ctime)
      totalTimeState = 'business.totalTimeStateComplete'
    }
    callBack({stepExpireTime, totalExpireTime, stepTimeState, totalTimeState})
  } else if (currentBusiness.history && currentBusiness.history.length === 0) {
    // 暂存工单
    let totalExpireTime, stepExpireTime
    let flowObj = getCache('businessFlow', currentBusiness.flow)
    if (flowObj.ctype && flowObj.ctime) {
      totalExpireTime = getTimeByMs(flowObj.ctype, flowObj.ctime)
      totalTimeState = 'business.totalTimeStateComplete'
      callBack({stepExpireTime, totalExpireTime, stepTimeState, totalTimeState})
    }
  } else {
    clearInterval(timeContent.stop)
    let totalExpireTime = currentBusiness.totalExpireTime || 0.1
    let stepExpireTime = currentBusiness.stepExpireTime || 0.1
    let timedown = function () {
      if (totalExpireTime !== 0.1) {
        if (totalExpireTime > 0) {
          totalTimeState = 'business.totalTimeStateUncomplete1'
        } else {
          totalTimeState = 'business.totalTimeStateUncomplete2'
        }
        totalExpireTime -= 1000
      } else {
      }
      if (stepExpireTime !== 0.1) {
        if (stepExpireTime > 0) {
          stepTimeState = 'business.stepTimeStateUncomplete1'
        } else {
          stepTimeState = 'business.stepTimeStateUncomplete2'
        }
        stepExpireTime -= 1000
      } else {
      }
      if (stepExpireTime === 0.1 && totalExpireTime === 0.1) {
        clearInterval(timeContent.stop)
      }
      callBack({stepExpireTime, totalExpireTime, stepTimeState, totalTimeState})
    }
    timedown()
    timeContent.stop = setInterval(timedown, 1000)
  }
}

export function advancedSearchBack (custom) {
  let result = {}
  for (let i in custom) {
    let key = i
    let filedKey = key
    if (key && key.split('_')) {
      filedKey = key.split('_')[0]
    }
    let field = getCache('businessFlowField', filedKey)
    if (field) {
      if (field.type === 'dropdownTree' || field.type === 'dropdown' || field.type === 'radio') {
        let dic = getDicByIdFor(custom[key], [getDicFromField(field, getCache('custTmpls'), getCache('options'))])
        if (dic && dic.key) {
          if (result[field.name]) {
            if (dic.name) {
              result[field.name] += (' ' + dic.name)
            }
          } else {
            result[field.name] = dic.name
          }
        }
      } else if (field.type === 'checkbox') {
        for (let m = 0; m < custom[key].length; m++) {
          let dic = getDicByIdFor(custom[key], [getDicFromField(field, getCache('custTmpls'), getCache('options'))] || [])
          if (dic) {
            if (result[field.name]) {
              if (dic.name) {
                result[field.name] += (' ' + dic.name)
              }
            } else {
              result[field.name] = dic.name
            }
          }
        }
      } else if (field.type === 'date') {
        if (custom[i]) {
          result[field.name] = custom[i].split(' ')[0]
        }
      } else if (field.type === 'time') {
        if (custom[i]) {
          result[field.name] = custom[i].split(' ')[1]
        }
      } else {
        if (custom[i]) {
          result[field.name] = custom[i]
        }
      }
    }
  }
  return result
}
/**
 * 工单超时时间，转化为秒
 * @param ctype 时间类型
 * @param ctime 时间数量
 * @returns number
 */
export function parseIntTime (ctype, ctime) {
  let time = parseInt(ctime) || 0
  if (ctype === 'hours' || ctype === 'hour') {
    time = time * 60
  } else if (ctype === 'day') {
    time = time * 60 * 24
  }
  return time
}
/**
 * 工单超时时间
 * @param ctype 时间类型
 * @param ctime 时间数量
 * @returns String
 */

export let timeTrans = (function () {
  let timeType = {
    min: '分钟',
    hours: '小时',
    day: '天'
  }
  return function (ctype, ctime) {
    return ctime + timeType[ctype]
  }
})()
/*
* 根据字段返回对应的字典
* @param {Object} field 字段信息
* @param {Array} custTmps 客户模版
* @param {Array} options 全部字典
* */
export let getDicFromField = function (field, custTmps, options) {
  if (field.relevance && field.relevance !== 'no') {
    let customFields = custTmps[0] && custTmps[0].custom_fields
    if (!customFields) {
      return
    }
    let data = field.relevance.split('_')
    let type = data[0]
    let key = data[1]
    if (key === 'province') {
      // 客户固定字段'省市县'从字典里取
      return options.filter((item) => {
        return item.accountId === 'system' && item.name === '省市县'
      })[0]
    } else if (type === 'custom') {
      // 客户自定义字段
      let customField = customFields.filter((item) => {
        return item._id === key
      })[0]
      if (!customField) {
        // 客户自定义字段被删除
        return {
          cascade: 1,
          options: []
        }
      } else if (customField.dic && customField.dic.isDic) {
        // 存在dic从字典取数据
        return options.filter((item) => {
          return item._id === customField.dic.dicId
        })[0]
      } else if (customField.choices) {
        // 把choices 格式化成字典格式
        let choices = customField.choices || {}
        let option = []
        for (let i in choices) {
          option.push({name: choices[i], key: i})
        }
        return {
          flag: customField.type,
          cascade: 1,
          options: option
        }
      }
    }
  } else if (field.dic) {
    return options.filter((item) => {
      return item._id === field.dic
    })[0]
  }
}
/*
* 根据字段和客户信息，返回默认值
* @param {Object} field 字段信息
* @param {Object} custInfo 客户信息
* @return {String | Array}
* */
export let getDefaultFromCustomer = function (field, custInfo, callInfo) {
  if (field.relevance && field.relevance !== 'no') {
    let data = field.relevance.split('_')
    let custType = data[0] // 客户固定字段或自定义字段
    let key = data[1]
    // let type = field.type
    let defaultValue = ''
    if (!custInfo[key]) {
      return ''
    }
    if (custType === 'stable' && key !== 'province') {
      if (key === 'phone') {
        // 隐藏号码
        if (callInfo && Object.keys(callInfo).length && custInfo.phone && custInfo.phone.length >= 1) { // 有通话信息 && 客户信息中的号码不止一个(默认绑定当前通话的号码)
          let callTel = callInfo.CALLED_NO
          if (callInfo.CONNECT_TYPE === 'normal' || callInfo.CONNECT_TYPE === 'transfer') {
            callTel = callInfo.CALL_NO
          }
          defaultValue = callTel || ''
        } else {
          defaultValue = custInfo.phone && custInfo.phone[0] && custInfo.phone[0].tel
        }
      } else if (key === 'email') {
        defaultValue = custInfo.email && custInfo.email[0] && custInfo.email[0].email
      } else if (key === 'weixin') {
        defaultValue = custInfo.weixin && custInfo.weixin[0] && custInfo.weixin[0].num
      } else {
        defaultValue = custInfo[key]
      }
    } else {
      if (field.type === 'dropdown' || field.type === 'dropdownTree' || field.type === 'checkbox') {
        defaultValue = typeof custInfo[key] === 'string' ? [custInfo[key]] : custInfo[key]
        // 如果key为province，默认值加上 市和县
        key === 'province' && defaultValue.push(custInfo.city, custInfo.district)
      } else if (field.type === 'radio') {
        defaultValue = custInfo[key]
      } else {
        let dic = getDicFromField(field, getCache('custTmpls'), getCache('options'))
        // flag存在，则字典来自客户自定义字段
        if (dic && (dic.flag === 'radio' || dic.flag === 'dropdown')) {
          defaultValue = getLabelFromOption([custInfo[key]], dic.options)[0]
        } else if (dic && dic.flag === 'checkbox') {
          let arr = custInfo[key] instanceof Array ? custInfo[key] : []
          defaultValue = arr.map((item) => {
            return getLabelFromOption([item], dic.options)[0] || ''
          }).join(', ')
        } else if (dic) {
          let ids = key === 'province' ? [custInfo.province, custInfo.city, custInfo.district] : custInfo[key]
          // 处理客户字段类型变更导致的报错
          if (ids instanceof Array) {
            defaultValue = getLabelFromOption(ids, dic.options).join('-->')
          } else {
            defaultValue = ids
          }
        } else {
          defaultValue = custInfo[key]
        }
      }
    }
    return defaultValue
  }
}
/*
* 根据ids获取级联select的各级label标签
* @param {Array} ids 5级联动的id
* @param {Array} options 字典里的options
* @return {Array} labels ids对应的labels
* */
function getLabelFromOption (ids, options, labels = []) {
  if (!ids[0]) {
    return labels
  }
  ids = [...ids]
  for (let i = 0; i < options.length; i++) {
    let item = options[i]
    if (item.key === ids[0]) {
      labels.push(item.name)
      ids.shift()
      getLabelFromOption(ids, item.options || [], labels)
      break
    }
  }
  return labels
}

export let fieldsExtend = function (items, flowFields, cb) {
  for (let i = 0; i < items.length; i++) {
    let row = items[i]
    for (let j = 0; j < row.cols.length; j++) {
      let col = row.cols[j]
      for (let k = 0; k < col.fields.length; k++) {
        let field = col.fields[k]
        let cacheField = getObjectById(flowFields, field._id) || {}
        cacheField['default'] = cb(cacheField)
        Object.assign(field, cacheField)
      }
    }
  }
  return items
}


export let strToArr = function (str, c = ';') {
  return uniq(str.split(c).map((item) => {
    return trim(item)
  }).filter(Boolean))
}
